package com.supor.aiot.home.ui.device.config;

import android.content.Context;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import com.alibaba.fastjson.JSONObject;
import com.android.baseconfig.base.BaseSharedPreferences;
import com.android.baseconfig.common.callback.OnItemClickListener;
import com.android.baseconfig.common.utils.SystemUtils;
import com.supor.aiot.common.app.AppAgent;
import com.supor.aiot.common.app.Constants;
import com.supor.aiot.common.entity.ProductType;
import com.supor.aiot.common.helper.GlobalDataCache;
import com.supor.aiot.common.utils.BitmapUtil;
import com.supor.aiot.home.R;
import com.supor.aiot.home.bean.ConfigItem;
import com.supor.aiot.home.bean.PingResult;
import com.supor.aiot.home.helper.APHelper;
import com.supor.aiot.home.helper.DataCache;
import com.supor.aiot.home.view.ConfigFailedDialog;

import java.util.ArrayList;
import java.util.List;

/**
 * ---------------------------------------------------------------- <br>
 * Copyright (C) 2014-2021, by het, ShenZhen, All rights reserved.  <br>
 * ---------------------------------------------------------------- <br>
 * <p>
 * 描述: 配网步骤容器 <br>
 * 作者: lei <br>
 * 日期: 2021/10/19 <br>
 */
public class WifiConfigContainer {
    public Context context;
    LinearLayout container;
    List<ConfigItem> itemList;
    /**
     * 当前配网item
     */
    ConfigItem configItem;
    private String countdownTip;
    private String mac;
    private String etvErrorMsg;
    private ConfigFailedDialog failedDialog;
    private OnItemClickListener clickListener;
    private ProductType.ProductModel productModel;

    public WifiConfigContainer(Context context, LinearLayout container) {
        this.context = context;
        this.container = container;
        itemList = new ArrayList<>();
        countdownTip = context.getString(R.string.bind_step2_countdown);
    }

    public void setClickListener(OnItemClickListener clickListener) {
        this.clickListener = clickListener;
    }

    public void setProductModel(ProductType.ProductModel productModel) {
        this.productModel = productModel;
    }

    public void addItem() {
        ConfigItem item = new ConfigItem(context, itemList.size());
        item.setViewClickListener(new ViewClick(item.index));
        if (productModel != null) {
            if (!TextUtils.isEmpty(productModel.crmModelName)) {
                item.tvDevice.setText(productModel.crmModelName);
                item.tvDeviceFailed.setText(String.format("%s%s", productModel.crmModelName,
                        context.getString(R.string.bind_config_failed)));
            } else {
                item.tvDevice.setText(String.format("%s%s", productModel.modelTypeName,
                        productModel.modelName));
                item.tvDeviceFailed.setText(String.format("%s%s", productModel.modelTypeName,
                        context.getString(R.string.bind_config_failed)));
            }
            BitmapUtil.loadUrl(productModel.modelPicture, item.ivDevice);
        }
        configItem = item;
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        params.rightMargin = context.getResources().getDimensionPixelSize(R.dimen.dp_11);
        params.leftMargin = context.getResources().getDimensionPixelSize(R.dimen.dp_11);
        params.topMargin = context.getResources().getDimensionPixelSize(R.dimen.dp_2);
        params.bottomMargin = context.getResources().getDimensionPixelSize(R.dimen.dp_2);
        container.addView(item.root, params);
    }

    /**
     * 倒计时
     *
     * @param count 倒计时数
     */
    public void countdown(int count) {
        configItem.tvStep3Countdown.setText(String.format(countdownTip, count));
    }

    /**
     * 步骤1完成状态
     *
     * @param result
     */
    public void onStep1(APHelper.Step result) {
        switch (result) {
            case SUCCESS:
                configItem.ivStepStatus1.setVisibility(View.VISIBLE);
                configItem.ivStepStatus1.setImageResource(R.mipmap.ic_bind_right);
                configItem.indicatorStep1.setVisibility(View.INVISIBLE);
                configItem.tvConfigLine1.setVisibility(View.VISIBLE);
                configItem.llConfigFailed.setVisibility(View.GONE);

                if (WifiConfigActivity.hasStepTwo) {
                    configItem.tvStep2.setTextColor(context.getResources().getColor(R.color.black));
                    configItem.indicatorStep2.setVisibility(View.VISIBLE);
                    configItem.ivStepStatus2.setVisibility(View.INVISIBLE);
                } else {
                    configItem.indicatorStep3.setVisibility(View.VISIBLE);
                    configItem.ivStepStatus3.setVisibility(View.INVISIBLE);
                    configItem.tvStep3.setTextColor(context.getResources().getColor(R.color.black));
                    configItem.tvStep3Countdown.setVisibility(View.VISIBLE);
                }
                // ivStepBg.setImageResource(R.mipmap.ic_net_config2);
                // configItem.indicatorStep2.setVisibility(View.VISIBLE);
                // configItem.ivStepStatus2.setVisibility(View.GONE);
                // configItem.tvStep2.setTextColor(getResources().getColor(R.color.black));
                // configItem.tvStep2Countdown.setVisibility(View.VISIBLE);
                // presenter.startTimer();

                break;
            case FAILURE:
                configItem.ivStepStatus1.setVisibility(View.VISIBLE);
                configItem.ivStepStatus1.setImageResource(R.mipmap.ic_bind_error);
                configItem.indicatorStep1.setVisibility(View.INVISIBLE);
                configItem.llConfigFailed.setVisibility(View.VISIBLE);
                break;
            default:
                break;
        }
    }

    /**
     * 步骤1.1完成状态（检测网络）
     *  @param result 0-正常|1-异常
     * @param pingResult ping result
     * @param ifStartStep11
     */
    public void onStep2(int result, PingResult pingResult, boolean ifStartStep11) {
        if (result == 0) {
            configItem.ivStepStatus2.setVisibility(View.VISIBLE);
            configItem.ivStepStatus2.setImageResource(R.mipmap.ic_bind_right);
            configItem.indicatorStep2.setVisibility(View.INVISIBLE);
            configItem.tvStep2.setText(context.getResources().getString(R.string.bind_step11_success));
            configItem.tvConfigLine2.setVisibility(View.VISIBLE);

            configItem.indicatorStep3.setVisibility(View.VISIBLE);
            configItem.ivStepStatus3.setVisibility(View.INVISIBLE);
            configItem.tvStep3.setTextColor(context.getResources().getColor(R.color.black));
            configItem.tvStep3Countdown.setVisibility(View.VISIBLE);
        } else {
            if ("100%".equalsIgnoreCase(pingResult.loss) || !ifStartStep11) {
                configItem.ivStepStatus2.setVisibility(View.VISIBLE);
                configItem.ivStepStatus2.setImageResource(R.mipmap.ic_bind_error);
                configItem.indicatorStep2.setVisibility(View.INVISIBLE);
                configItem.tvStep2.setText(context.getResources().getString(R.string.bind_step11_error));

                // configItem.llConfigStep12.setVisibility(View.VISIBLE);
                // configItem.llConfigStep3.setVisibility(View.INVISIBLE);
            }
        }
    }

    /**
     * 步骤2完成状态
     *
     * @param bindData 不为空-成功|等于空-失败
     */
    public void onStep3(String bindData) {
        if (bindData != null) {
            configItem.ivStepStatus3.setVisibility(View.VISIBLE);
            configItem.ivStepStatus3.setImageResource(R.mipmap.ic_bind_right);
            configItem.indicatorStep3.setVisibility(View.INVISIBLE);
            configItem.tvStep3.setText(R.string.bind_step2_success);

            configItem.tvStep3Countdown.setVisibility(View.GONE);
            configItem.llConfigFailed.setVisibility(View.GONE);

            showDevice(bindData);
        } else {
            configItem.ivStepStatus3.setVisibility(View.VISIBLE);
            configItem.ivStepStatus3.setImageResource(R.mipmap.ic_bind_error);
            configItem.indicatorStep3.setVisibility(View.INVISIBLE);
            configItem.tvStep3.setText(R.string.bind_step2_error);
            configItem.tvStep3Countdown.setVisibility(View.GONE);
            onMac(this.mac);
            configItem.llConfigFailed.setVisibility(View.VISIBLE);
        }
    }

    private void showDevice(String bindData) {
        if (productModel == null) {
            JSONObject object = JSONObject.parseObject(bindData);
            String model = object.getString("productModel");
            for (ProductType productType : GlobalDataCache.productTypeList) {
                if (productType.Children != null) {
                    for (ProductType.ProductModel child : productType.Children) {
                        if (model.equalsIgnoreCase(child.modelName)) {
                            setProductModel(child);
                            if (productModel != null) {
                                if (!TextUtils.isEmpty(productModel.crmModelName)) {
                                    configItem.tvDevice.setText(productModel.crmModelName);
                                    configItem.tvDeviceFailed.setText(String.format("%s%s", productModel.crmModelName,
                                            context.getString(R.string.bind_config_failed)));
                                } else {
                                    configItem.tvDevice.setText(String.format("%s%s", productModel.modelTypeName,
                                            productModel.modelName));
                                    configItem.tvDeviceFailed.setText(String.format("%s%s", productModel.modelTypeName,
                                            context.getString(R.string.bind_config_failed)));
                                }
                                BitmapUtil.loadUrl(productModel.modelPicture, configItem.ivDevice);
                            }
                            return;
                        }
                    }
                }
            }
        }

    }

    /**
     * mac
     */
    public void onMac(String mac) {
        if (mac != null) {
            this.mac = mac.toUpperCase();
            String nativeVersion = SystemUtils.getVerName(AppAgent.getApp());
            String tinyVersion = BaseSharedPreferences.getString(AppAgent.getApp(),
                    Constants.Key.param_tinyVersion, "");
            if (TextUtils.isEmpty(tinyVersion)) {
                etvErrorMsg = String.format(context.getString(R.string.bind_step2_error_msg_1),
                        DataCache.CURRENT_SSID, DataCache.CURRENT_PWD);
            } else {
                etvErrorMsg = String.format(context.getString(R.string.bind_step2_error_msg_1),
                        DataCache.CURRENT_SSID, DataCache.CURRENT_PWD);
            }
        }
    }

    public void hideDialog() {
        if (failedDialog != null && failedDialog.isShowing()) {
            failedDialog.dismiss();
        }
    }

    public boolean isDialogShow() {
        return failedDialog != null && failedDialog.isShowing();
    }
    
    public class ViewClick implements View.OnClickListener {

        private final int index;

        public ViewClick(int index) {
            this.index = index;
        }

        @Override
        public void onClick(View v) {
            if (v.getId() == R.id.tv_check_reason) {
                // if (failedDialog != null && failedDialog.isShowing()) {
                //     failedDialog.dismiss();
                // }
                ConfigFailedDialog.Builder builder = new ConfigFailedDialog.Builder(context);
                builder.setMessage(etvErrorMsg);
                builder.setPositiveButton(context.getResources().getString(R.string.bind_retry_config), (dialog, which) -> {
                    if (clickListener != null) {
                        clickListener.onItemClick(v, index);
                    }
                });
                builder.setNegativeButton(context.getResources().getString(R.string.cancel), (dialog, which) -> dialog.dismiss());
                failedDialog = builder.create();
                failedDialog.setCancelable(false);
                failedDialog.show();
            }
        }
    }
}
